package core.sim.elfarol;

import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.util.*;

import stats.*;

import core.*;
import core.genetic.*;
import core.neural.*;
import core.sim.*;

public class SimpleSparseSim implements SingleSimulation{

	@Override
	public int getSurroungingsCount() {
		return 0;
	}
	

	@Override
	public int getInfluencesCount() {
		return 1;
	}
	
	@Override
	public int getInputCounts() {
		return 1+Mode.mode.FEROMONS+Mode.mode.MEMORY;
	}

	@Override
	public int getOutputCounts() {
		return getInfluencesCount()+Mode.mode.FEROMONS+Mode.mode.MEMORY;
	}

	public int turns;
	
	public SimpleSparseSim(int turns) {
		this.turns = turns;
	}
	
	@Override
	public double[] playSimulation(Individual[] individuals) {
		int n = individuals.length;
		double[][] feromons = new double[n][Mode.mode.brain.FEROMONS];
		double[][] memory = new double[n][Mode.mode.brain.MEMORY];
		
		double[][] outputs = new double[n][]; 
		
		for(int i = 0;i<=turns;i++) {
			for(int j = 0;j<n;j++)
				outputs[j] = Mode.mode.brain.calculateOutputs(individuals[j], BrainParsing.mergeInputs(new double[0], feromons[j], memory[j]));
			
			if (i<turns)
			{
				for(int j = 0;j<n;j++)
					for(int k = 0;k<Mode.mode.brain.FEROMONS;k++)
						feromons[j][k] = 0;					
			
				for(int j = 0;j<n;j++)
				{
					double[][] splitted = BrainParsing.splitOutput(outputs[j]);
					System.arraycopy(splitted[BrainParsing.MEMORY_POS], 0, memory[j], 0, Mode.mode.brain.MEMORY);
					for(int k = 0;k<n;k++)
						if (j!=k) {
							for(int t = 0;t<Mode.mode.brain.FEROMONS;t++)
								feromons[k][t]+=splitted[BrainParsing.FEROMONS_POS][t];
						}
				}
			}
		}					
		
		
		double[] guesses = new double[n];		
		for(int i = 0;i<n;i++) 
			guesses[i] = outputs[i][0];		
		
		Arrays.sort(guesses);
//		System.out.print(Arrays.toString(guesses));
		for(int i = 0;i<n;i++) {			
			if (guesses[i]<0) guesses[i] = 0;
			else if (guesses[i]>1) guesses[i] = 1;			
		}
//		System.out.println("  -  " + Arrays.toString(guesses));
		double max = Double.POSITIVE_INFINITY;
		for(int i = 0;i+1<n;i++)
			max = Math.min(max, guesses[i+1]-guesses[i]);		
		
		Statistics.addTeamResult(max);
		
		double[] res = new double[n];		
		for(int i = 0;i<n;i++)
			res[i] = max;
		return res;
	}


	@Override
	public void drawSimulation(Population pop, double[] values) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void drawMovie(Graphics2D g2, Point2D dim) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void executeForMovie(Individual[] individuals) {
		// TODO Auto-generated method stub
		
	}



}
